package com.qf.controller;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAd;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsPermissonService;
import com.qf.service.DtsRolesService;
import com.qf.util.Base64;
import com.qf.util.ResponseUtil;
import com.qf.util.UUID;
import com.qf.util.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.ObjIntConsumer;

@RestController
@RequestMapping("/admin/auth")
@CrossOrigin("http://localhost")
public class AdminAuthController {
    @Autowired
    DtsRolesService rolesService;
    @Autowired
    DtsPermissonService permissonService;

    /**
     *用户注销
     * @return
     */
//    @RequiresAuthentication
//    @RequestMapping("logout")
//    public Object loginOut(){
//        Subject subject=SecurityUtils.getSubject();
//        subject.logout();
//        logger.info()
//        return ResponseUtil.ok();
//    }



    @RequestMapping("/info")
    public Object info(){
        //获取主体对象
        Subject subject=SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
        //获取角色Id数组
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = rolesService.findByRoleIds(roleIds);
        Set<String> perms = permissonService.findByRoleIds(roleIds);

        Map<String,Object>data=new HashMap<>();
        data.put("roles",roles);
        data.put("name",admin.getUsername());
        data.put("perms",perms);
        data.put("avatar",admin.getAvatar());

        return ResponseUtil.ok(data);
    }
    @RequestMapping("/login")
    //将返回的值全部存入map集合中
    public Object login(@RequestBody Map<String,Object> map){
        System.out.println(map);
        //从集合中取出验证码
        String  code =(String) map.get("code");
        //从集合中取出uuid
        String  uuid =(String ) map.get("uuid");
        //调用该方法从缓存区中将uuid以验证码的方式取出
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        //校验验证码
        if(!cachedCaptcha.equalsIgnoreCase(code)||cachedCaptcha==null){
            return ResponseUtil.fail(-1,"验证码已过期");
        }
        //获取用户名，密码
        String  username =(String) map.get("username");
        String  password =(String) map.get("password");
        try {
            //校验用户
            Subject subject= SecurityUtils.getSubject();
            //创建token对象
            UsernamePasswordToken token=new UsernamePasswordToken(username,password);
            //执行登录操作要跟数据库中的用户名密码进行校验
            subject.login(token);
            Serializable id = subject.getSession().getId();
            System.out.println(subject.hasRole("超级管理员"));
            return ResponseUtil.ok(id);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"用户名不存在");
        }catch (CredentialsException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"密码不正确");
        }catch (LockedAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"账户已锁定");
        }catch (AuthenticationException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"认证失败");
        }
    }
    @RequestMapping("/logout")
    public Object logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResponseUtil.ok();
    }
    @RequestMapping("/captchaImage")
    public  Object captchaImage() throws IOException {
        //获取验证码
        String s = VerifyCodeUtils.generateVerifyCode(2);
        String uuid = UUID.randomUUID().toString();
        //把验证码存到缓存中
        CaptchaCodeManager.addToCache(uuid,s,1);
        ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
        //生成图片
        VerifyCodeUtils.outputImage(111,36, outputStream,s);
        Map<String,Object> data=new HashMap<>();
        data.put("uuid",uuid);
        data.put("img", Base64.encode(outputStream.toByteArray()));
        return ResponseUtil.ok(data);
    }
}
